<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input disabled v-model="model.purchaseBill" placeholder="请输入单据编号"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep placeholder="请选择申请人" v-model="model.proposer" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
                  <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled" v-model="model.departId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep placeholder="请选择申请人" :disabled="formDisabled" v-model="model.employeeId" @back="backUserInfo"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart placeholder="请选择申请单位" :disabled="formDisabled" v-model="model.applicant" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="出库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryType">
                  <a-select
                    v-model="model.deliveryType"
                    :disabled="formDisabled"
                    placeholder="请输入出库方式"
                    :allowClear="true"
                    @change="handleChange"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in deliveryTypeList" :key="item.value" :value="item.value">{{item.text}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.deliveryType === '0'">
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <select-project-input v-model="model.projectId" placeholder="请选择关联项目" :disabled="formDisabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.deliveryType === '4'">
                <a-form-model-item label="关联调拨单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cannibalizeId">
                  <select-purchase-cannibalizelist-input :disabled="formDisabled" v-model="model.cannibalizeId"></select-purchase-cannibalizelist-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.deliveryType === '5'">
                <a-form-model-item label="关联物品领用单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialId">
                  <select-purchase-goodsreceivelist-input :disabled="formDisabled" deliveryStorage="0" v-model="model.materialId" @back="materialIdBack"></select-purchase-goodsreceivelist-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="仓管员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storer">
                  <select-user-by-dep placeholder="请选择仓管员" :disabled="formDisabled" v-model="model.storer" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="出库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryDate">
                  <j-date :disabled="formDisabled" placeholder="请选择出库日期" :show-time="true" v-model="model.deliveryDate" date-format="YYYY-MM-DD HH:mm"  style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="出库方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryManner">
                  <j-dict-select-tag :disabled="formDisabled" v-model="model.deliveryManner" dictCode="	delivery_manner" placeholder="请输入出库方式"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input placeholder="请选择申请团队" :disabled="formDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="出库单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryUnit">
                  <j-select-company :disabled="formDisabled" v-model="model.deliveryUnit" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="24">
                <a-form-model-item label="出库摘要" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="abstracts">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.abstracts" rows="4" placeholder="请输入出库摘要"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="出库明细">
            <erp-purchase-warehouse-delivery-detail-list ref="delivery" :disabled="formDisabled" :storer="model.storer" :deliveryType="model.deliveryType"></erp-purchase-warehouse-delivery-detail-list>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { mapGetters } from 'vuex';
import { ajaxGetDictItems } from '@/api/api'
import moment from 'moment';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import SelectPurchaseCannibalizelistInput from '@/views/scy/components/SelectPurchaseCannibalizelistInput'
import SelectPurchaseGoodsreceivelistInput from '@/views/scy/components/SelectPurchaseGoodsreceivelistInput'
import ErpPurchaseWarehouseDeliveryDetailList from './reference/ErpPurchaseWarehouseDeliveryDetailList.vue'

export default {
    name: 'ErpPurchaseWarehouseDeliveryForm',
    mixins: [viewFile],
    components: {
      ErpPurchaseWarehouseDeliveryDetailList,
      ViewFileModal,
      SelectUserByDep,
      SelectTeamInput,
      SelectProjectInput,
      SelectPurchaseCannibalizelistInput,
      SelectPurchaseGoodsreceivelistInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        activeKey: ['1','2','3'],
        model:{
          purchaseBill: null
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          // employeeId: [
          //     { required: true, message: '请选择申请人!', trigger: 'change'},
          // ],
          // applicant: [
          //     { required: true, message: '请选择申请单位!', trigger: 'change'},
          // ],
          // departId: [
          //     { required: true, message: '请选择申请部门!', trigger: 'change'},
          // ],
          deliveryType: [
              { required: true, message: '请选择出库类型!', trigger: 'blur'},
          ],
          storer: [
              { required: true, message: '请选择仓管员!', trigger: 'change'},
          ],
          deliveryDate: [
              { required: true, message: '请选择出库日期!', trigger: 'change'},
          ],
          deliveryManner: [
              { required: true, message: '请选择出库方式!', trigger: 'blur'},
          ],
          // deliveryUnit: [
          //     { required: true, message: '请选择出库单位!', trigger: 'change'},
          // ],
          teamId: [
              { required: true, message: '请选择申请团队!', trigger: 'change'},
          ],
          abstracts: [
              { required: true, message: '请输入出库摘要!', trigger: 'blur'},
          ],
        },
        url: {
          add: "/api/erp/purchase/storehouse/erpPurchaseWarehouseDelivery/add",
          edit: "/api/erp/purchase/storehouse/erpPurchaseWarehouseDelivery/edit",
          queryById: "/api/erp/purchase/storehouse/erpPurchaseWarehouseDelivery/queryById",
          gainBillNo: "/api/erp/purchase/storehouse/erpPurchaseWarehouseDelivery/gainBillNo",
          materialIdList: '/api/erp/purchase/recipients/erpPurchaseRecipientsDetail/allListTo'
        },
        deliveryTypeList: []
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      ...mapGetters(['userInfo']),
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res)=>{
          if(res.success){
            that.model.purchaseBill = res.result//单据编号
          }
        })
      },
      findDataCodeList() {
        ajaxGetDictItems('delivery_type').then(res => {
          if (res.success) {
            this.deliveryTypeList = res.result
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        this.getBillNo()
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.proposer = this.userInfo().empId; // 当前登录人
        this.model.departId = this.userInfo().deptId; //当前登录人部门
        this.model.storer = this.userInfo().empId; //仓管员
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      },
      edit (record) {
        this.findDataCodeList()
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.delivery.loadData(1, this.model.id)
        } else {
          this.$refs.delivery.dataSource = []
        }
        //其他
        if(this.model.deliveryType === '5'){
          this.$refs.delivery.addFlag = false
        } else {
          this.$refs.delivery.addFlag = true
        }
        if(!!this.model.deliveryType) {
          this.$refs.delivery.handleChangeDeliveryType(this.model.deliveryType)
        } else {
          this.$refs.delivery.handleChangeDeliveryType()
        }
        this.visible = true;
      },
      handleChange(value) {
        this.$set(this.model, 'cannibalizeId', null)
        this.$set(this.model, 'materialId', null)
        this.$set(this.model, 'projectId', null)
        if(value === '0'){
          this.$refs.form.clearValidate('cannibalizeId');
          this.$refs.form.clearValidate('materialId');
          this.$set(this.validatorRules, 'projectId', [
            { required: true, message: '请选择关联项目!', trigger: 'change'},
          ])
        }
        if(value === '4'){
          this.$refs.form.clearValidate('projectId');
          this.$refs.form.clearValidate('materialId');
          this.$set(this.validatorRules, 'cannibalizeId', [
            { required: true, message: '请选择关联调拨申请单!', trigger: 'change'},
          ])
        }
        if(value === '5'){
          this.$refs.form.clearValidate('cannibalizeId');
          this.$refs.form.clearValidate('projectId');
          this.$set(this.validatorRules, 'materialId', [
            { required: true, message: '请选择关联物品领用单!', trigger: 'change'},
          ])
        }
        //其他
        if(value === '5'){
          this.$refs.delivery.addFlag = false
        } else {
          this.$refs.delivery.addFlag = true
        }
        this.$refs.delivery.dataSource = []
        this.$refs.delivery.handleChangeDeliveryType(value)
      },
      submitForm () {
        let details = this.$refs.delivery.submitForm()
        if(!details.length > 0) {
          this.$message.warning('请添加出库明细信息！');
          this.$emit('unButtonDisable');
          return
        }
        //其他类
        if(this.model.deliveryType == 5) {
          //循环判断子表数据是否完善
          for (let index = 0; index < details.length; index++) {
            const element = details[index];
            if(isNaN(element.purchaseNum) || isNaN(element.deliveryAmount) || isNaN(element.deliveryNum) || !element.storehouseId) {
              this.$message.warning('请完善出库明细信息中的必填项！');
              this.$emit('unButtonDisable');
              return
            }
          }
        }
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.detailList = details
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error)=>{
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }

        })
      },
      // backUserInfo(data) {
      //   this.model.applicant = data[0].orgDepart;//申请人单位
      //   this.model.departId = data[0].departmentId;//申请人部门
      // }
      materialIdBack(value) {
        if(value.length > 0) {
          let materialDataSource = []
          const that = this;
          let parem = { billId: value[0].id}
          if(!!this.model.id) {
            parem.deliveryId = this.model.id
          }
          getAction(this.url.materialIdList, parem).then(res => {
            if (res.success) {
              //设置子表数据
              for (var i = 0; i < res.result.length; i++) {
                let element = res.result[i]
                let dataOne = {}
                dataOne.key = i
                dataOne.provisionBroad = element.provisionBroad//物料大类
                dataOne.provisionSmall = element.provisionSmall//物料小类
                dataOne.materialBillId = element.materialBillId//物料编号
                dataOne.materialName = element.materialName//物料名称
                dataOne.specification = element.specification//规格型号
                dataOne.unit = element.unit//单位
                dataOne.brand = element.brand//品牌
                dataOne.companName = element.companName//供应商
                dataOne.purchaseNum = element.recipientsNum//领用数量
                dataOne.deliveryAmount = element.deliveryAmount//累计出库数量
                dataOne.childId = element.id//关联子表id
                materialDataSource.push(dataOne)
              }
              that.$refs.delivery.dataSource = materialDataSource
            }else{
              that.$message.warning(res.message);
            }
          })
        }
      }
    }
  }
</script>
